from django.shortcuts import render
from django import forms
from django.contrib.auth import authenticate
from django.views.generic import FormView,RedirectView
from django.urls import reverse_lazy
from django.contrib.auth import login,logout
from django.http import JsonResponse

# Create your views here.
#表单类
class LoginForm(forms.Form):
    username = forms.CharField()
    password = forms.CharField()

    def login(self):
        #鉴权并返回user对象
        user =  authenticate(username = self.cleaned_data['username'],password = self.cleaned_data['password'])
        return user

#登录类视图
class LoginView(FormView):
    #模版名称
    template_name = 'authentication/user_login.html'
    success_url = reverse_lazy('homepage')
    
    form_class = LoginForm
    
    #获取提交的数据
    def get_context_data(self, **kwargs):
        context = super(LoginView, self).get_context_data(**kwargs)
        context['active_page'] = 'login'
        return context

    #表单数据验证
    def form_valid(self, form):
        user = form.login()
        if user is not None:
            login(self.request,user)
            return JsonResponse({"state":'success'})
        else:
            return JsonResponse({'state':'error','msg':'用户名或密码错误'})

#登出类视图
class LogoutView(RedirectView):
    pattern_name = 'homepage'
    
    def get_redirect_url(self, *args, **kwargs):
        logout(self.request)
        return super(LogoutView, self).get_redirect_url(*args,**kwargs)